/*
 * Copyright (c) Jiandong.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

import { NumberUtil } from './YogaUtils';
import { YogaConstants } from './YogaConstants';
import { YogaUnit } from './YogaUnit';
export class YogaValue {
  public static readonly UNDEFINED = new YogaValue(YogaConstants.UNDEFINED, YogaUnit.UNDEFINED);
  public static readonly ZERO = new YogaValue(0, YogaUnit.POINT);
  public static readonly AUTO = new YogaValue(YogaConstants.UNDEFINED, YogaUnit.AUTO);

  public readonly value: number;
  public readonly unit: YogaUnit;

  public constructor(value: number, unit: number) {
    this.value = value;
    this.unit = unit;
  }

//  YogaValue(float value, int unit) {
//    this(value, YogaUnit.fromInt(unit));
//  }

//   @Override
  public equals(other: any) {
    if (other instanceof YogaValue) {
        const otherValue: YogaValue =  other as YogaValue;
        if (this.unit == otherValue.unit) {
          return this.unit == YogaUnit.UNDEFINED
              || this.unit == YogaUnit.AUTO
              || this.value == otherValue.value;
        }
    }
    return false;
  }

//   @Override
  public hashCode(): number {
    return NumberUtil.floatToIntBits(this.value) + this.unit;
  }

//   @Override
  public toString(): string | never {
    switch (this.unit) {
      case YogaUnit.UNDEFINED:
        return "undefined";
      case YogaUnit.POINT:
        return this.value.toString();
      case YogaUnit.PERCENT:
        return this.value + "%";
      case YogaUnit.AUTO:
        return "auto";
      default:
        throw new Error();
    }
  }

  public static parse(s: string): YogaValue {
    if (s == null) {
      return null;
    }
  
    if ("undefined" === s) {
      return YogaValue.UNDEFINED;
    }
  
    if ("auto" === s) {
      return YogaValue.AUTO;
    }
  
    if (s.endsWith("%")) {
      return new YogaValue(parseFloat(s.substring(0, s.length - 1)), YogaUnit.PERCENT);
    }
  
    return new YogaValue(parseFloat(s), YogaUnit.POINT);
  }
}
